package com.efounder.frame.manager;

import android.app.Application;
import android.util.Log;

import com.core.xml.StubObject;
import com.efounder.frame.bean.MyThemeBean;
import com.efounder.mobilemanager.R;
import com.efounder.service.Registry;
import com.efounder.util.EnvSupportManager;
import com.efounder.widget.skinview.SkinCustomViewInflater;
import com.utilcode.util.SPUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import skin.support.SkinCompatManager;
import skin.support.app.SkinAppCompatViewInflater;
import skin.support.app.SkinCardViewInflater;
import skin.support.constraint.app.SkinConstraintViewInflater;
import skin.support.design.app.SkinMaterialViewInflater;
import skin.support.flycotablayout.app.SkinFlycoTabLayoutInflater;

/**
 * 主题管理
 *
 * @autor yqs
 * @date 2019/1/29 14:05
 **/
public class ThemeManager {
    private static final String TAG = "ThemeManager";
    private Application applicationContext;
    private static volatile ThemeManager themeManager;
    //皮肤包本地目录
    private String skinDir;

    public static ThemeManager getInstance(Application application) {
        if (themeManager == null) {
            themeManager = new ThemeManager(application);
        }
        return themeManager;
    }

    private ThemeManager(Application application) {
        this.applicationContext = application;
    }

    /**
     * 初始化换肤控件
     */
    public void initSkinSupport(String skinDir) {
        //不支持换肤，直接返回
        if (!EnvSupportManager.isSupportSkin()) {
            return;
        }
        this.skinDir = skinDir;

        //androidsupport 初始化
//        SkinCompatManager.withoutActivity(applicationContext)
//                .addStrategy(new CustomSDCardLoader(skinDir))          // 自定义加载策略，指定SDCard路径
//                .addInflater(new SkinCustomViewInflater())    // pansoft 自定义
//                .addInflater(new SkinMaterialViewInflater())    // material design
//                .addInflater(new SkinConstraintViewInflater())  // ConstraintLayout
//                .addInflater(new SkinFlycoTabLayoutInflater())  // H07000223/FlycoTabLayout
//                .addInflater(new SkinCardViewInflater())
//                .setSkinStatusBarColorEnable(true)
//                .loadSkin();


        //androidx初始化
        SkinCompatManager.withoutActivity(applicationContext)
                .addStrategy(new CustomSDCardLoader(skinDir))          // 自定义加载策略，指定SDCard路径
                .addInflater(new SkinCustomViewInflater())    // pansoft 自定义
                .addInflater(new SkinAppCompatViewInflater())           // 基础控件换肤初始化
                .addInflater(new SkinMaterialViewInflater())            // material design 控件换肤初始化[可选]
                .addInflater(new SkinConstraintViewInflater())          // ConstraintLayout 控件换肤初始化[可选]
                .addInflater(new SkinCardViewInflater())                // CardView v7 控件换肤初始化[可选]
                //.addInflater(new SkinFlycoTabLayoutInflater())  // H07000223/FlycoTabLayout
//                .addInflater(new SkinCardViewInflater())
                .setSkinStatusBarColorEnable(true)
                .loadSkin();
        if (EnvSupportManager.isSupportSkin()) {
            initSelectedSkin();
        }
    }

    /**
     * 获取所有可使用的主题列表
     *
     * @return
     */
    public List<MyThemeBean> getThemeList() {
        List<MyThemeBean> list = new ArrayList<>();
        MyThemeBean currentSkin = getCurrentSkin();
        //todo 查询应用内皮肤
        String[] titles = applicationContext.getResources().getStringArray(R.array.app_theme_title);
        String[] suffixs = applicationContext.getResources().getStringArray(R.array.app_theme_suffix);
        for (int i = 0; i < titles.length; i++) {
            String suffix = suffixs[i];
            int type = MyThemeBean.TYPE_IN_APP;
            if (suffix.equals("default")) {
                type = MyThemeBean.TYPE_IN_DEFAULT;
            }

            MyThemeBean bean = new MyThemeBean.Builder().themeTitle(titles[i]).themeName(suffix)
                    .type(type).build();

            //设置当前选中的
            if (currentSkin.getType() == MyThemeBean.TYPE_IN_DEFAULT && bean.getType() == MyThemeBean.TYPE_IN_DEFAULT) {
                bean.setSelected(true);
            } else if (currentSkin.getType() == bean.getType()
                    && currentSkin.getThemeName().equals(bean.getThemeName())) {
                bean.setSelected(true);
            }
            list.add(bean);

        }
        //todo sdcard的插件式皮肤
        List<StubObject> skinsList = Registry.getRegEntryList("skins");
        if (skinsList != null) {
            for (int i = 0; i < skinsList.size(); i++) {
                int type = MyThemeBean.TYPE_OUT_APP;

                MyThemeBean bean = new MyThemeBean.Builder().themeTitle(skinsList.get(i).getCaption())
                        .themeName(skinsList.get(i).getString("skinName", ""))
                        .type(type).build();
                //设置当前选中的
                if (currentSkin.getType() == MyThemeBean.TYPE_IN_DEFAULT
                        && bean.getType() == MyThemeBean.TYPE_IN_DEFAULT) {
                    bean.setSelected(true);
                } else if (currentSkin.getType() == bean.getType()
                        && currentSkin.getThemeName().equals(bean.getThemeName())) {
                    bean.setSelected(true);
                }
                list.add(bean);
            }
        }

        return list;
    }

    //初始化之前选中的皮肤
    private void initSelectedSkin() {
        MyThemeBean bean = getCurrentSkin();
        if (bean.getType() != MyThemeBean.TYPE_IN_DEFAULT) {
            //不是默认皮肤，那么我们进行换肤操作
            try {
                changeSkin(bean, new SkinCompatManager.SkinLoaderListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onFailed(String errMsg) {
                        restoreDefaultTheme();
                    }
                });
            } catch (Exception e) {
                Log.e(TAG, "换肤失败");
                restoreDefaultTheme();
            }
        }
    }

    /**
     * 获取当前使用的主题
     *
     * @return
     */
    public MyThemeBean getCurrentSkin() {
        int skinType = SPUtils.getInstance().getInt("skinType", MyThemeBean.TYPE_IN_DEFAULT);
        String skinName = SPUtils.getInstance().getString("skinName", "");
        if (skinName.equals("")) {
            skinType = MyThemeBean.TYPE_IN_DEFAULT;
        }
        MyThemeBean bean = new MyThemeBean.Builder().themeName(skinName)

                .type(skinType).build();

        return bean;
    }

    public String getSkinTitle(String skinName) {
        List<MyThemeBean> list = getThemeList();
        for (int i = 0; i < list.size(); i++) {
            MyThemeBean item = list.get(i);
            if (item.getThemeName().equals(skinName)) {
                return item.getThemeTitle();
            }
        }
        return "";
    }

    /**
     * 设置当前使用的主题
     *
     * @return
     */
    public void setCurrentSkin(MyThemeBean skin) {
        SPUtils.getInstance().put("skinType", skin.getType());
        SPUtils.getInstance().put("skinName", skin.getThemeName());
    }

    /**
     * 更换皮肤
     *
     * @return
     */
    public void changeSkin(MyThemeBean skin) {
        changeSkin(skin, null);
    }

    /**
     * 更换皮肤
     *
     * @param skin               皮肤信息
     * @param skinLoaderListener 换肤监听
     * @return
     */
    public void changeSkin(MyThemeBean skin, SkinCompatManager.SkinLoaderListener skinLoaderListener) {
        if (skin == null) {
            return;
        }
        if (skin.getType() == MyThemeBean.TYPE_IN_DEFAULT) {
            // 恢复应用默认皮肤
            restoreDefaultTheme();
            if (skinLoaderListener != null) {
                skinLoaderListener.onSuccess();
            }
        } else if (skin.getType() == MyThemeBean.TYPE_IN_APP) {
            // 加载应用内皮肤
            SkinCompatManager.getInstance().loadSkin(skin.getThemeName(), skinLoaderListener, SkinCompatManager.SKIN_LOADER_STRATEGY_BUILD_IN); // 后缀加载
        } else if (skin.getType() == MyThemeBean.TYPE_OUT_APP) {
            //插件式换肤，读取文件
            File file = new File(skinDir, skin.getThemeName());
            if (file != null && file.exists()) {
                SkinCompatManager.getInstance().loadSkin(skin.getThemeName(), skinLoaderListener, CustomSDCardLoader.SKIN_LOADER_STRATEGY_SDCARD);
            }
        }
    }


    /**
     * 恢复应用默认皮肤
     */
    public void restoreDefaultTheme() {
        SkinCompatManager.getInstance().restoreDefaultTheme();
        SPUtils.getInstance().put("skinType", MyThemeBean.TYPE_IN_DEFAULT);
        SPUtils.getInstance().put("skinName", "");
    }
}
